package com.dongjiantong.farmrecords.serviceImpl;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.dongjiantong.common.exceptions.HttpCode;
import com.dongjiantong.common.exceptions.OPServerException;
import com.dongjiantong.common.utils.ReportNumberMakerUtil;
import com.dongjiantong.common.web.sso.LoginInfo;
import com.dongjiantong.farmrecords.enums.FarmRecordsFileEnum;
import com.dongjiantong.farmrecords.enums.FarmRecordsNumberStatus;
import com.dongjiantong.farmrecords.mapper.FarmRecordsFeedMapper;
import com.dongjiantong.farmrecords.mapper.FarmRecordsFileMapper;
import com.dongjiantong.farmrecords.model.FarmRecordsFeed;
import com.dongjiantong.farmrecords.model.FarmRecordsFile;
import com.dongjiantong.farmrecords.service.FarmRecordsFeedService;
import com.dongjiantong.farmrecords.service.FarmRecordsFileService;
import com.dongjiantong.mybatis.ServiceMybatis;
import com.dongjiantong.user.enums.FarmsEnum;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 生产中心 -- 饲料记录
 */
@Slf4j
@Service(version = "1.0.0")
public class FarmRecordsFeedServiceImpl extends ServiceMybatis<FarmRecordsFeed> implements FarmRecordsFeedService {

   @Resource
    private FarmRecordsFeedMapper farmRecordsFeedMapper;
   @Resource
   private FarmRecordsFileMapper farmRecordsFileMapper;

   @Resource
   private FarmRecordsFileService farmRecordsFileService;


    @Override
    public PageInfo<FarmRecordsFeed> selectByMap(Integer pageNum, Integer pageSize, Map map) {
        try {
            if (farmRecordsFeedMapper == null){
                throw new OPServerException("farmRecordsFeedMapper 为null,请检查");
            }
            PageHelper.startPage(pageNum,pageSize);
            //查询有效单据
            map.put("delete_flag", FarmRecordsNumberStatus.EFFECTIVE.getCode());
            //查询已启用的养殖场
            map.put("farmStatus", FarmsEnum.status_true.getCode());
            List<FarmRecordsFeed> list = farmRecordsFeedMapper.selectByMap(map);
            if (list.size() > 0){
                this.setPicOrVideoList(list);
            }
            return new PageInfo<FarmRecordsFeed>(list);
        } catch (Exception e) {
            log.error(e.getMessage());
            throw new OPServerException(HttpCode.INTERNAL_SERVER_ERROR.getCode(),HttpCode.INTERNAL_SERVER_ERROR.getMessage());
        }
    }

    /**
     * 设置关联信息(视频,图片)
     * @param farmRecordsFeedList
     */
    public void setPicOrVideoList(List<FarmRecordsFeed> farmRecordsFeedList){
        if (farmRecordsFileMapper == null){
            throw new OPServerException("farmRecordsFileMapper 为null,请检查");
        }
        List<Long> ids = farmRecordsFeedList.stream().map(farmRecordsFeed -> farmRecordsFeed.getId()).collect(Collectors.toList());

        List<Integer> type2List = Lists.newArrayList(FarmRecordsFileEnum.PHOTO.getCode(),FarmRecordsFileEnum.VIDEO.getCode());

        Map map = Maps.newHashMap();
        map.put("relevanceIds",ids);
        map.put("listType2",type2List);
        map.put("type1",FarmRecordsFileEnum.FEED.getCode());
        //查询对应的图片,视频
        List<FarmRecordsFile> farmRecordsFileList = farmRecordsFileMapper.selectPicOrVideoListByRelevanceIds(map);

        if (farmRecordsFileList.size() > 0){
            for (FarmRecordsFeed farmRecordsFeed : farmRecordsFeedList){
                this.setPicOrVideoByObject(farmRecordsFeed,farmRecordsFileList);
            }
        }
    }

    /**
     * 放入图片 视频信息到对象中
     * @param farmRecordsFeed
     * @param farmRecordsFileList
     */
    @Override
    public FarmRecordsFeed setPicOrVideoByObject(FarmRecordsFeed farmRecordsFeed,List<FarmRecordsFile> farmRecordsFileList) {
        List<String> picList = null;
        List<String> videoList = null;
        for (FarmRecordsFile farmRecordsFile : farmRecordsFileList){
            if ((farmRecordsFeed.getId()).equals(farmRecordsFile.getRelevance_id())){
                JSONArray jsonArray = JSON.parseArray(farmRecordsFile.getAddress());
                List<String> list = jsonArray.toJavaList(String.class);
                //获取图片
                if ((FarmRecordsFileEnum.PHOTO.getCode()).equals(farmRecordsFile.getType2())){
                    picList = list;
                }
                //获取视频
                if ((FarmRecordsFileEnum.VIDEO.getCode()).equals(farmRecordsFile.getType2())){
                    videoList = list;
                }
            }
        }
        //设置图片
        if (picList != null && picList.size() > 0){
            farmRecordsFeed.setPicList(picList);
        }
        //设置视频
        if (videoList != null && videoList.size() > 0){
            farmRecordsFeed.setVideoList(videoList);
        }

        return farmRecordsFeed;
    }

    /**
     * 新建一条记录 (暂存状态下)
     * @param farmRecordsFeed
     * @param toStatus
     * @return  long 返回插入数据的id
     */
    @Override
    public Long createOne(LoginInfo loginInfo,FarmRecordsFeed farmRecordsFeed, Integer toStatus) {
        try {
            if (farmRecordsFeedMapper == null){
                throw new OPServerException("farmRecordsFeedMapper 为null,请检查");
            }
            Integer fromStatus = farmRecordsFeed.getStatus();

            //todo 生成单据号
            //单据生成规则暂未定(此处为测试)
            String prefix = "SSL";
            prefix = ReportNumberMakerUtil.createPrefix(prefix,loginInfo.getProvinceId(),loginInfo.getCityId(),loginInfo.getRegionId());
            String maxNumber = farmRecordsFeedMapper.findMaxNumber(prefix);
            String number = ReportNumberMakerUtil.create(prefix,maxNumber);
            farmRecordsFeed.setNumber(number);

            farmRecordsFeed.setProvince_id(loginInfo.getProvinceId());
            farmRecordsFeed.setCity_id(loginInfo.getCityId());
            farmRecordsFeed.setRegion_id(loginInfo.getRegionId());
            farmRecordsFeed.setStreet_id(loginInfo.getStreetId());
            farmRecordsFeed.setVillage_id(loginInfo.getVillageId());

            farmRecordsFeed.setDelete_flag(FarmRecordsNumberStatus.EFFECTIVE.getCode());

            farmRecordsFeed.setCreated_at(new Date());
            farmRecordsFeed.setUpdated_at(new Date());

            if (fromStatus == 0 && toStatus == null) {
                //直接暂存
                farmRecordsFeedMapper.createOne(farmRecordsFeed);
            }else if (!fromStatus.equals(toStatus) && FarmRecordsNumberStatus.SUBMIT.getCode().equals(toStatus)){
                //直接提交
                farmRecordsFeed.setStatus(toStatus);
                farmRecordsFeedMapper.createOne(farmRecordsFeed);
            }

            if (farmRecordsFeed.getId() != 0) {
                farmRecordsFileService.insertPicOrVideoByRelevanceId(FarmRecordsFileEnum.FEED.getCode(),farmRecordsFeed.getPicList(),farmRecordsFeed.getVideoList(),Long.valueOf(farmRecordsFeed.getId()));
            }

            //todo 生成日志记录

            return farmRecordsFeed.getId();
        } catch (Exception e) {
            log.error(e.getMessage());
            throw new OPServerException(HttpCode.DATA_CREATE_FAIL,HttpCode.DATA_CREATE_FAIL.getMessage());
        }
    }

    /**
     * 更新一条记录 (根据id或者number)
     * @param farmRecordsFeed
     * @return  boolean (更新成功返回true 反之返回false)
     */
    @Override
    public Integer updateByIdOrNumber(FarmRecordsFeed farmRecordsFeed,Integer toStatus) {
        try {
            if (farmRecordsFeedMapper == null){
                throw new OPServerException("farmRecordsFeedMapper 为null,请检查");
            }

            farmRecordsFeed.setStatus(toStatus);
            farmRecordsFeed.setUpdated_at(new Date());
            Integer con = farmRecordsFeedMapper.updateByPrimaryKeySelective(farmRecordsFeed);

            farmRecordsFileService.updatePicOrVideoByRelevanceId(FarmRecordsFileEnum.FEED.getCode(),farmRecordsFeed.getPicList(),farmRecordsFeed.getVideoList(),Long.valueOf(farmRecordsFeed.getId()));

            return con;
        } catch (Exception e) {
            log.error(e.getMessage());
            throw new OPServerException(HttpCode.DATA_UPDATE_FAIL,HttpCode.DATA_UPDATE_FAIL.getMessage());
        }
    }

    /**
     * 养殖端
     * 根据提交状态分页查询列表
     * @param farmId
     * @param status
     * @return
     */
    @Override
    public PageInfo<FarmRecordsFeed> selectListByStatus(Integer pageNum, Integer pageSize, Integer status, Long farmId) {
        PageHelper.startPage(pageNum,pageSize);

        Map<String,Object> map = Maps.newHashMap();

        if (status != null) {
            map.put("status",status);
        }

        map.put("farm_id",farmId);
        map.put("delete_flag",FarmRecordsNumberStatus.EFFECTIVE.getCode());

        List<FarmRecordsFeed> farmRecordsFeedList = farmRecordsFeedMapper.selectListByStatus(map);

        if (farmRecordsFeedList.size() > 0) {
            this.setPicOrVideoList(farmRecordsFeedList);
        }

        return new PageInfo<FarmRecordsFeed>(farmRecordsFeedList);
    }

    /**
     * 根据养殖场id 和时间区间查询饲料消耗总量
     * @param farmId
     * @param startDate
     * @param endDate
     * @return
     */
    @Override
    public Float selectTotalQuantity(Long farmId, Date startDate, Date endDate) {
        Map<String,Object> map = Maps.newHashMap();
        if (farmId != null) {
            map.put("farmId",farmId);
        }
        if (startDate != null) {
            map.put("startDate",startDate);
        }
        if (endDate != null) {
            map.put("endDate",endDate);
        }
        Float feed = farmRecordsFeedMapper.selectQuantityByFarmId(map);
        return feed;
    }
}
